/* 
 * CS:APP Data Lab 
 * 
 * <Please put your name and userid here>
 * 
 * bits.c - Source file with your solutions to the Lab.
 *          This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the <stdio.h> header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * <stdio.h>, although you might get a compiler warning. In general,
 * it's not good practice to ignore compiler warnings, but in this
 * case it's OK.  
 */

#if 0
/*
 * Instructions to Students:
 *
 * STEP 1: Read the following instructions carefully.
 */

You will provide your solution to the Data Lab by
editing the collection of functions in this source file.

INTEGER CODING RULES:
 
  Replace the "return" statement in each function with one
  or more lines of C code that implements the function. Your code 
  must conform to the following style:
 
  int Funct(arg1, arg2, ...) {
      /* brief description of how your implementation works */
      int var1 = Expr1;
      ...
      int varM = ExprM;

      varJ = ExprJ;
      ...
      varN = ExprN;
      return ExprR;
  }

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. Unary integer operations ! ~
  4. Binary integer operations & ^ | + << >>
    
  Some of the problems restrict the set of allowed operators even further.
  Each "Expr" may consist of multiple operators. You are not restricted to
  one operator per line.

  You are expressly forbidden to:
  1. Use any control constructs such as if, do, while, for, switch, etc.
  2. Define or use any macros.
  3. Define any additional functions in this file.
  4. Call any functions.
  5. Use any other operations, such as &&, ||, -, or ?:
  6. Use any form of casting.
  7. Use any data type other than int.  This implies that you
     cannot use arrays, structs, or unions.

 
  You may assume that your machine:
  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting if the shift amount
     is less than 0 or greater than 31.


EXAMPLES OF ACCEPTABLE CODING STYLE:
  /*
   * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
   */
  int pow2plus1(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     return (1 << x) + 1;
  }

  /*
   * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
   */
  int pow2plus4(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     int result = (1 << x);
     result += 4;
     return result;
  }

FLOATING POINT CODING RULES

For the problems that require you to implement floating-point operations,
the coding rules are less strict.  You are allowed to use looping and
conditional control.  You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants. You can use any arithmetic,
logical, or comparison operations on int or unsigned data.

You are expressly forbidden to:
  1. Define or use any macros.
  2. Define any additional functions in this file.
  3. Call any functions.
  4. Use any form of casting.
  5. Use any data type other than int or unsigned.  This means that you
     cannot use arrays, structs, or unions.
  6. Use any floating point data types, operations, or constants.


NOTES:
  1. Use the dlc (data lab checker) compiler (described in the handout) to 
     check the legality of your solutions.
  2. Each function has a maximum number of operations (integer, logical,
     or comparison) that you are allowed to use for your implementation
     of the function.  The max operator count is checked by dlc.
     Note that assignment ('=') is not counted; you may use as many of
     these as you want without penalty.
  3. Use the btest test harness to check your functions for correctness.
  4. Use the BDD checker to formally verify your functions
  5. The maximum number of ops for each function is given in the
     header comment for each function. If there are any inconsistencies 
     between the maximum ops in the writeup and in this file, consider
     this file the authoritative source.

/*
 * STEP 2: Modify the following functions according the coding rules.
 * 
 *   IMPORTANT. TO AVOID GRADING SURPRISES:
 *   1. Use the dlc compiler to check that your solutions conform
 *      to the coding rules.
 *   2. Use the BDD checker to formally verify that your solutions produce 
 *      the correct answers.
 */


#endif
//1
/* 
 * bitXor - x^y using only ~ and & 
 *   Example: bitXor(4, 5) = 1
 *   Legal ops: ~ &
 *   Max ops: 14
 *   Rating: 1
 */
int bitXor(int x, int y) {
  int var1 = x & (~y);
  int var2 = (~x) & y;
  int var3 = (~var1) & (~var2);
  return ~var3;
}
/* 
 * tmin - return minimum two's complement integer 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmin(void) {
  return 1 << 31;

}
//2
/*
 * isTmax - returns 1  if x is the maximum, two's complement number,
 *     and 0 otherwise 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTmax(int x) {
  // satisfy the expresion '(x + 1) == ~x' just for -1 and Tmax
  // -1 + 1 = 0, howerver Tmax + 1 = Tmin
  // so we could combind above two condition to judge whether x is Tmax

  int var1 = x + 1;
  int var2 = var1 ^ (~x);
  // use '!' twice is to convert var from int to bool
  // as I cannot think another better idea
  return !!var1 & !var2;
}
/* 
 * allOddBits - return 1 if all odd-numbered bits in word set to 1
 *   where bits are numbered from 0 (least significant) to 31 (most significant)
 *   Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 2
 */
int allOddBits(int x) {
  // In order to explain the solution,
  // I use lowercase to indicate origin value, uppercase to indicate
  // not value
  // Let assume the bit length of our parameter x is eight to simply our
  // problem
  // Example: x  is    '1a1b1c1d' which satisfies the requirement <1>
  // Then x >> 1 is    '11a1b1c1' <2>
  // Then <1> & <2> is '1aabbccd' <3>
  // Then <2> ^ <3> is '0A0B0C0D' <4>
  // Then ~<4>, we get '1a1b1c1d' <5>, which just the value of x
  // So, we could take the process above to testify whether x
  // satisfies the requirement
  
  /*int var1 = x >> 1; // <2>
  int var2 = x & var1; // <3>
  int var3 = var1 ^ var2; // <4>
  int var4 = ~var3; // <5>
  return !(var4 ^ x);*/

  // Maybe I was too simple to code.
  // In fact, I think this method has offend the taboo.
  // So I did not decide to apply that to solve the problem.
  // However, I have no other better choices.

  int mask = 0xaa;
  mask |= mask << 8;
  mask |= mask << 16; 
  return !((x & mask) ^ mask);
}
/* 
 * negate - return -x 
 *   Example: negate(1) = -1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int negate(int x) {
  return ~x + 1;
}
//3
/* 
 * isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
 *   Example: isAsciiDigit(0x35) = 1.
 *            isAsciiDigit(0x3a) = 0.
 *            isAsciiDigit(0x05) = 0.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 3
 */
int isAsciiDigit(int x) {
  // After thinking a long time, I decide to apply the knowledge about
  // digital logic circuit to testify whether the low 4 bits of x is in
  // [0,9], however the process would consume seven operations, which is
  // also not elegant.
  // [31:6]110xxx or [31:6]11100x is the format of x which satisfies the
  // requirement. 

  int var1 = x >> 6; // record the high 26 bits of x
  int var2 = x & 0x38;
  int var3 = x & 0x3e;
  int var4 = !(var2 ^ 0x30);
  int var5 = !(var3 ^ 0x38);
  return (!var1) & (var4 | var5);
}
/* 
 * conditional - same as x ? y : z 
 *   Example: conditional(2,4,5) = 4
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 16
 *   Rating: 3
 */
int conditional(int x, int y, int z) {
  // Referencd by data selector described in digital logical cricuit,
  // I want to construct a or expression which would implements the
  // effect that when 'x' is zero, the expresion selects 'y', while 
  // selects 'z'.
  // However, I have taken a long time a design such expresion.
  // Then I will explain my idea.
  // Firstly reference a variable named bool_x which represents the 
  // bool value of 'x'.
  // Then construct two complicated expression below.
  // ~(~(!bool_x)+1) --- <1>
  // ~(~bool_x+1)    --- <2>
  // <1> would become the left and operator of 'y'. 
  // <2> would become the right and operator of 'z'.
  // When bool_x is zero, the value of <1> is 0 and the value of <2> is ~0.
  // When bool_x is one, the value of <1> is ~0 and the value of <2> is 0.
  // Then we could write the final expression "<1> & 'y' | <2> & 'z'".

  //int not_x = !x; // The not value of 'x'
  //int var1 = ~(~not_x + 1);
  //int var2 = ~(~(!not_x) + 1);
  //return (var1 & y) | (var2 & z);

  // I have thought another better solution which is similar to 'cmov'
  // instruction.
  // Let's declare a variable named 'ret' and then assign 'ret' with 'y'.
  // Then we can write the final expression 'ret ^= (y ^ z) & control'.
  // 'control' is expression which value is influenced by 'x'.
  // If x = 0, then control is ~0 and ret is 'z'.
  // Else, then control is 0 and ret is 'y'.
  // We could easily construct such control expression '~(!x) + 1'.
  
  int not_x = !x;
  int ret = y;
  int control = ~not_x + 1;
  ret ^= (y ^ z) & control;
  return ret;
}
/* 
 * isLessOrEqual - if x <= y  then return 1, else return 0 
 *   Example: isLessOrEqual(4,5) = 1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 24
 *   Rating: 3
 */
int isLessOrEqual(int x, int y) {
  // Compute x - y and check the symbol bit of result to judge whether
  // x is equal or less than y
  // However, there may exists overflow phenomenon which would 
  // interrupt our result.

  /*int neg_y = ~y + 1;
  int x_minus_y = x + neg_y;
  int symbol = (x_minus_y >> 31) & 1; // if x <= y, then symbol is 1
                                      // else, then symbol is 0
  return symbol;*/

  // So I have to judge whether it occurs overflow according to
  // symbol bit of two operators and result.
  // We could design a logical expression using three variable
  // 'x_symbol', 'y_symbol' and 'minus_symbol'.
  // The expression is ('x_symbol' | 'minus_symbol') & 
  // (!'y_symbol' | 'minus_symbol') & (!'y_symbol' & 'x_symbol').
  // However 0x80000000 - 0x80000000 is a trap!
  // So we should add a variable named control and again construct
  // logical expression!

  // In fact logical expression always consume ammounts of ops, we
  // should choose better expression instead logical expression.
  // if 'x_symbol' is complement with 'y_symbol', return 'x_symbol'
  // else then return 'minus_symbol'
  // However, we should care about the trap caused by 0x80000000 whose
  // negative number is still 0x80000000.
  // So we should add another or operator 'equal_flag' to solve such
  // trap.

  // Attention: when 'x' is pos while 'y' is neg, ('x_symbol' ^ 'y_symbol')
  // & 'x_symbol' is 0, and then would compute 'x' - 'y'.
  // Maybe my explanation is somewhat abstract.
  // Assuming that we think of the or expression in the aspect of control
  // structure, then the process is below.
  // 'x' == 'y' ? return 1
  // 'x' is neg while 'y' is pos ? return 1
  // compute 'x' - 'y'
  //  both 'x' and 'y' are pos(neg) ? return 'minus_symbol'
  // finally, return 0 (correspond to the case when 'x' is pos and 'y' is
  // neg)
  // So we should add a variable named 'control' whose value is 'x_symbol'
  // ^ 'y_symbol' to control the result.
 
  int x_symbol = (x >> 31) & 1;
  int y_symbol = (y >> 31) & 1;
  int control = x_symbol ^ y_symbol;
  int neg_y = ~y + 1;
  int minus = (x + neg_y);
  int minus_symbol = (minus >> 31) & 1;
  int equal_flag = !(x ^ y);
  return equal_flag | (
         (control & x_symbol) | 
         (minus_symbol & (!control))); 
}
//4
/* 
 * logicalNeg - implement the ! operator, using all of 
 *              the legal operators except !
 *   Examples: logicalNeg(3) = 0, logicalNeg(0) = 1
 *   Legal ops: ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 4 
 */
int logicalNeg(int x) {
  // If the value of 'x' is 0, then ('x' ^ -'x') is 0
  // else, then ('x' ^ -'x') is a negative integer
  // So we could apply the speciality to testify whether x is 0; 
  // However, 0x80000000 is a trap!

  int neg_x = ~x + 1;
  int tmin = 1 << 31;
  int symbol = (x ^ neg_x) >> 31; // if x is zero, then symbol is 0x0
                                  // while symbol is 0xffffffff
  int control = (x ^ tmin) >> 31; // used to select 0, reject 0x80000000
  return (symbol + 1) & control;
}
/* howManyBits - return the minimum number of bits required to represent x in
 *             two's complement
 *  Examples: howManyBits(12) = 5
 *            howManyBits(298) = 10
 *            howManyBits(-5) = 4
 *            howManyBits(0)  = 1
 *            howManyBits(-1) = 1
 *            howManyBits(0x80000000) = 32
 *  Legal ops: ! ~ & ^ | + << >>
 *  Max ops: 90
 *  Rating: 4
 */
int howManyBits(int x) {
  // Maybe we should depend on magic to solve such a difficult problem.
  // Below that is the best solution I could think using loop structure.

  /*int target = x >> 31; // the destination of sar 
  int count = 0;
  while(x != target) {
    x >>= 1;
    count += 1;
  }
  return count + 1;*/

  // Below I attempts to use binary-search to reduce loop count.

  /*int target, low, mid, high, temp;
  target = x >> 31;
  low = 0;
  high = 31;
  while(low < high) {
    mid = (low + high) >> 1;
    temp = x >> mid;
    // if I could use conditional expression, even copying the loop body
    // five times, I would still satisfy the requirement of max ops.
    // However, I cannot use conditional expression.           
    if(temp == target)
      high = mid;
    else
      low = mid + 1;
  }
  return low + 1;*/

  // After thinking a long time, I have conceived a solution to optimize 
  // the conditional expression which would satisfies the requirement 
  // about max ops even coping the loop body five times.
  // However, I do not think that is a good solution which has amounts of
  // repeat code.
  
  int target = x >> 31;     // the destination of sars
  int low = 0;         
  int high = 31;
  int mid;                  // used for binary-search
  int temp;                 // record the result of sars
  int control;              // used for condition
  int not_temp_xor_target;  // the factor of control
  
  // The loop body would consume 15 ops.
  // After repeating five times, it would just consume 75 ops.
 
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
 
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);

  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);

  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
  
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
  
  // Thanks to binary-search, even repeatedly exceuting unnecessary  
  // code, it would always get the right answer.

  return low + 1;
} 
//float
/* 
 * floatScale2 - Return bit-level equivalent of expression 2*f for
 *   floating point argument f.
 *   Both the argument and result are passed as unsigned int's, but
 *   they are to be interpreted as the bit-level representation of
 *   single-precision floating point values.
 *   When argument is NaN, return argument
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 30
 *   Rating: 4
 */
unsigned floatScale2(unsigned uf) {
  // I think this is comparativly easier than the question above.
  // if uf is 0, return 0
  // if uf is denorm, left shift the fraction part of uf
  // if uf is INF, return INF
  // if uf is NaN, return NaN

  int exponent_mask = 0x7f800000; // select the exponent part of float
  int fraction_mask = 0x7fffff;
  int exponent = (uf & exponent_mask) >> 23;
  int fraction = (uf & fraction_mask);
  
  if(!exponent) {
      if(fraction) {
          fraction <<= 1;
          uf &= ~fraction_mask; // reset the fraction part of float
  	  uf |= fraction;
      }    
      return uf;
  }		
  if(exponent == 255) 
	return uf; 	
  exponent += 1;
  uf &= ~exponent_mask; // reset the exponent part of float
  uf |= exponent << 23;
  return uf;
}
/* 
 * floatFloat2Int - Return bit-level equivalent of expression (int) f
 *   for floating point argument f.
 *   Argument is passed as unsigned int, but
 *   it is to be interpreted as the bit-level representation of a
 *   single-precision floating point value.
 *   Anything out of range (including NaN and infinity) should return
 *   0x80000000u.
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 30
 *   Rating: 4
 */
int floatFloat2Int(unsigned uf) {
  // exponent is 0, return 0
  // exponent is 255, return 0x80000000u
  // Later we will call 'exponent - bias' 'actual exponent' to 
  // better explain my solution.
  // actual exponent in [-126, -2], return 0
  // actual exponent is -1, return 1
  // actual exponent in [0,22], return S0...01xxx
  // actual exponent in [23,30], return S0...01xxx0...0
  // actual exponent in [31,127], return 0x80000000u
   
  int exponent_mask = 0x7f800000; // select the exponent part of float
  int fraction_mask = 0x7fffff;
  int exponent = (uf & exponent_mask) >> 23;
  int actual_exponent = exponent - 127;
  int fraction = (uf & fraction_mask);
  int symbol = (uf >> 31);
  int res;
 
  if(!exponent || actual_exponent <= -1)
      return 0;
  if(exponent == 255 || actual_exponent >= 31)
      return 0x80000000;
  res = 1;
  if(actual_exponent < 23) {
      res <<= actual_exponent; // prepare location for fraction
      res |= (fraction >> (23 - actual_exponent)); // load fraction
  }
  else {
      res <<= 23;
      res |= fraction;
      res <<= (actual_exponent - 23);
  }
  if(symbol)
      res = -res;
  return res;
}
/* 
 * floatPower2 - Return bit-level equivalent of the expression 2.0^x
 *   (2.0 raised to the power x) for any 32-bit integer x.
 *
 *   The unsigned value that is returned should have the identical bit
 *   representation as the single-precision floating-point number 2.0^x.
 *   If the result is too small to be represented as a denorm, return
 *   0. If too large, return +INF.
 * 
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. Also if, while 
 *   Max ops: 30 
 *   Rating: 4
 */
unsigned floatPower2(int x) {
    // We call 'exponent + bias' 'actual_exponent'
    // if actual_exponent < -149, return 0
    // if actual_exponent in [-149,-126), return denorm
    // if actual_exponent in [-126,128), return norm
    // if actual_exponent >= 128, return +INF

    unsigned uf;
    if(x < -149) 
        uf = 0;
    else if(x >= 128) 
        uf = 0x7f800000;
    else if(x < -126) 
    	uf = 1 << (x + 149);
    else 
	uf = (x + 127) << 23;
    return uf;
}
